import os
import subprocess
import re


class VideoSplitter:
    """视频切割工具类（基于 ffmpeg）"""

    def __init__(self):
        self.input_path = None
        self.time_points = ["02:00"]
        self.output_dir = os.path.join(os.path.expanduser("~"), "Desktop", "video_split")
        self.output_format = "mp4"

    # ======== setter 方法 ========
    def set_input_path(self, path: str):
        """设置输入视频路径"""
        if not os.path.exists(path):
            raise FileNotFoundError(f"视频文件不存在: {path}")
        self.input_path = path
        return self

    def set_time_points(self, points: list[str]):
        """设置分割时间点列表"""
        self.time_points = points
        return self

    def set_output_dir(self, path: str):
        """设置输出文件夹路径"""
        self.output_dir = path
        return self

    def set_output_format(self, fmt: str):
        """设置输出视频格式"""
        self.output_format = fmt
        return self

    # ======== 核心功能 ========

    @staticmethod
    def time_to_ffmpeg_format(time_str: str) -> str:
        """将时间字符串转换为 ffmpeg 可识别的 HH:MM:SS 格式"""
        parts = time_str.split(":")
        if len(parts) == 1:
            return f"00:00:{parts[0].zfill(2)}"
        elif len(parts) == 2:
            return f"00:{parts[0].zfill(2)}:{parts[1].zfill(2)}"
        elif len(parts) == 3:
            return f"{parts[0].zfill(2)}:{parts[1].zfill(2)}:{parts[2].zfill(2)}"
        else:
            raise ValueError(f"时间格式错误: {time_str}")

    @staticmethod
    def get_video_duration(input_path: str) -> str:
        """获取视频总时长（HH:MM:SS）"""
        result = subprocess.run(
            ["ffmpeg", "-i", input_path],
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            text=True,
            encoding="utf-8"  # 🔥 强制使用 UTF-8 解码
        )
        match = re.search(r"Duration:\s*(\d+):(\d+):(\d+\.\d+)", result.stdout)
        if not match:
            raise ValueError("无法获取视频时长，请确认 ffmpeg 可用且文件正常。")

        hours, minutes, seconds = match.groups()
        return f"{hours.zfill(2)}:{minutes.zfill(2)}:{int(float(seconds)):02d}"

    def split(self):
        """执行视频分割"""
        if not self.input_path:
            raise ValueError("未设置输入视频路径，请先调用 set_input_path()。")
        if not self.time_points:
            raise ValueError("未设置分割时间点，请先调用 set_time_points()。")

        os.makedirs(self.output_dir, exist_ok=True)

        # 转换时间点格式并排序
        points = sorted(self.time_to_ffmpeg_format(t) for t in self.time_points)

        # 添加起点和终点
        points = ["00:00:00"] + points
        duration = self.get_video_duration(self.input_path)
        points.append(duration)
        result=[]
        # 执行切割
        for i in range(len(points) - 1):
            start, end = points[i], points[i + 1]
            segment_index = f"{i + 1:02d}"
            output_file = os.path.join(
                self.output_dir,
                f"part_{segment_index}_{start.replace(':', '-')}_{end.replace(':', '-')}.{self.output_format}"
            )

            cmd = [
                "ffmpeg", "-y",
                "-i", self.input_path,
                "-ss", start,
                "-to", end,
                "-c:v", "libx264",
                "-c:a", "aac",
                "-strict", "experimental",
                output_file
            ]


            print(f"🎬 正在切割第 {segment_index} 段：{start} → {end}")
            subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=True)
            print(f"✅ 已导出：{output_file}")
            result.append(output_file)


        print("\n🚀 全部切割完成！")
        return result


# ======== 示例用法 ========
if __name__ == "__main__":
    splitter = VideoSplitter()
    splitter.set_input_path(r"C:\Users\33720\Desktop\123.mp4") \
            .set_time_points(["39:20", "41:30"]) \
            .set_output_dir(r"C:\Users\33720\Desktop\video_split") \
            .set_output_format("mp4")

    splitter.split()
